package cn.com.lanou.wechat.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.lanou.wechat.dao.WechatMapper;
import net.sf.json.JSONObject;

public class WechatUtil {
	@Autowired
	private WechatMapper wechatMapper;
	
	
	private static String appid = "wx539cf7e29ad2cfab";
	private static String secret="d2fbd4fd3ce84069c50898fb61278e9f";
	private Logger log = Logger.getLogger(WechatUtil.class);
	
	
	 public void getAccessToken(){  
	
		 HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(
					"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
							+ appid + "&secret=" + secret);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			UrlEncodedFormEntity entity = null;
			try {
				entity = new UrlEncodedFormEntity(params, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			httpPost.setEntity(entity);
			System.out.println("1111111111111");
			try {
				HttpResponse httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					HttpEntity httpEntity = httpResponse.getEntity();
					String res = EntityUtils.toString(httpEntity, "UTF-8");
					String access_token = String.valueOf(JSONObject.fromObject(res).get("access_token"));
					wechatMapper.upToken(access_token);
					log.info(res);
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }  
}
